﻿
namespace TouchPoint.ShapeEngine.Input.Voice
{
    using System;
    using System.Threading.Tasks;
    using Windows.Media.SpeechRecognition;
    public class Voice2TextService
    {
        private static uint HResultPrivacyStatementDeclined = 0x80045509;
        //---------------------------------------------------------------------------------------------------
        //  当前语音识别方法并未对识别失败的情况加以区分,请务必在今后更新相关的逻辑
        //  Updated:2017/8/18 22:08
        //  当前已经完成了错误捕捉
        //---------------------------------------------------------------------------------------------------
        async public Task<string> VoiceRecognize()
        {
            try
            {
                var speechRecognize = new SpeechRecognizer(SpeechRecognizer.SystemSpeechLanguage);
                await speechRecognize.CompileConstraintsAsync();
                var grammer = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.WebSearch, "WebSearch");
                var result = await speechRecognize.RecognizeWithUIAsync();
                return result.Text;
            }
            catch (Exception exception)
            {
                // Handle the speech privacy policy error.
                if ((uint)exception.HResult == HResultPrivacyStatementDeclined)
                {
                    // Open the privacy/speech, inking, and typing settings page.
                    await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-accounts"));
                }
                else
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog(exception.Message, "尝试开启语音识别的时候出现错误!");
                    await messageDialog.ShowAsync();
                }
                return string.Empty;
            }
        }
    }
}
